package org.lc.stk.web.controller.course;

import java.util.List;

import org.lc.stk.model.course.Chapter;
import org.lc.stk.service.course.ChapterService;
import org.lc.stk.web.dto.chapter.ChapterTreeResponseDTO;
import org.lc.stk.web.response.ApiResponse;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;

@RestController
@Tag(name = "章节管理", description = "课程章节的增删改查接口")
@SecurityRequirement(name = "bearerAuth")
public class ChapterController {

    private final ChapterService chapterService;

    public ChapterController(ChapterService chapterService) {
        this.chapterService = chapterService;
    }

    @PostMapping("/api/courses/{courseId}/chapters")
    @Operation(summary = "创建章节")
    @PreAuthorize("hasAnyRole('TEACHER', 'ADMIN')")
    public ResponseEntity<ApiResponse<Chapter>> createChapter(
            @Parameter(description = "课程ID") @PathVariable Integer courseId,
            @Parameter(description = "父章节ID（可选）") @RequestParam(required = false) Integer parentId,
            @RequestBody Chapter chapter) {
        Chapter created = chapterService.createChapter(courseId, parentId, chapter);
        return ResponseEntity.ok(ApiResponse.success(created));
    }

    @PutMapping("/api/chapters/{id}")
    @Operation(summary = "更新章节")
    @PreAuthorize("hasAnyRole('TEACHER', 'ADMIN')")
    public ResponseEntity<ApiResponse<Chapter>> updateChapter(
            @Parameter(description = "章节ID") @PathVariable Integer id,
            @RequestBody Chapter chapter) {
        Chapter updated = chapterService.updateChapter(id, chapter);
        return ResponseEntity.ok(ApiResponse.success(updated));
    }

    @DeleteMapping("/api/chapters/{id}")
    @Operation(summary = "删除章节")
    @PreAuthorize("hasAnyRole('TEACHER', 'ADMIN')")
    public ResponseEntity<ApiResponse<Void>> deleteChapter(
            @Parameter(description = "章节ID") @PathVariable Integer id) {
        chapterService.deleteChapter(id);
        return ResponseEntity.ok(ApiResponse.success());
    }

    @GetMapping("/api/chapters/{id}")
    @Operation(summary = "获取章节详情")
    @PreAuthorize("isAuthenticated()")
    public ResponseEntity<ApiResponse<Chapter>> getChapter(
            @Parameter(description = "章节ID") @PathVariable Integer id) {
        return chapterService.getChapterById(id)
                .map(chapter -> ResponseEntity.ok(ApiResponse.success(chapter)))
                .orElse(ResponseEntity.notFound().build());
    }

    @GetMapping("/api/courses/{courseId}/chapters")
    @Operation(summary = "获取课程的根章节列表")
    @PreAuthorize("isAuthenticated()")
    public ResponseEntity<ApiResponse<List<Chapter>>> getRootChapters(
            @Parameter(description = "课程ID") @PathVariable Integer courseId) {
        List<Chapter> chapters = chapterService.getRootChapters(courseId);
        return ResponseEntity.ok(ApiResponse.success(chapters));
    }

    @GetMapping("/api/courses/{courseId}/chapters/tree")
    @Operation(summary = "获取课程的章节树形结构")
    @PreAuthorize("isAuthenticated()")
    public ResponseEntity<ApiResponse<List<ChapterTreeResponseDTO>>> getChapterTree(
            @Parameter(description = "课程ID") @PathVariable Integer courseId) {
        List<ChapterTreeResponseDTO> tree = chapterService.getChapterTree(courseId);
        return ResponseEntity.ok(ApiResponse.success(tree));
    }

    @GetMapping("/api/chapters/{parentId}/children")
    @Operation(summary = "获取子章节列表")
    @PreAuthorize("isAuthenticated()")
    public ResponseEntity<ApiResponse<List<Chapter>>> getChildChapters(
            @Parameter(description = "父章节ID") @PathVariable Integer parentId) {
        List<Chapter> chapters = chapterService.getChildChapters(parentId);
        return ResponseEntity.ok(ApiResponse.success(chapters));
    }

    @PutMapping("/api/chapters/{id}/move")
    @Operation(summary = "移动章节顺序")
    @PreAuthorize("hasAnyRole('TEACHER', 'ADMIN')")
    public ResponseEntity<ApiResponse<Chapter>> moveChapter(
            @Parameter(description = "章节ID") @PathVariable Integer id,
            @Parameter(description = "新的排序号") @RequestParam Integer newSort) {
        Chapter moved = chapterService.moveChapter(id, newSort);
        return ResponseEntity.ok(ApiResponse.success(moved));
    }

    @GetMapping("/api/chapters/{id}/path")
    @Operation(summary = "获取章节的完整路径")
    @PreAuthorize("isAuthenticated()")
    public ResponseEntity<ApiResponse<String>> getChapterPath(
            @Parameter(description = "章节ID") @PathVariable Integer id) {
        String path = chapterService.getChapterPath(id);
        return ResponseEntity.ok(ApiResponse.success(path));
    }

    @GetMapping("/api/courses/{courseId}/chapters/search")
    @Operation(summary = "搜索章节")
    @PreAuthorize("isAuthenticated()")
    public ResponseEntity<ApiResponse<List<Chapter>>> searchChapters(
            @Parameter(description = "课程ID") @PathVariable Integer courseId,
            @Parameter(description = "章节名称") @RequestParam String name) {
        List<Chapter> chapters = chapterService.searchChapters(courseId, name);
        return ResponseEntity.ok(ApiResponse.success(chapters));
    }

    @GetMapping("/api/chapters/{id}/level")
    @Operation(summary = "获取章节的层级")
    @PreAuthorize("isAuthenticated()")
    public ResponseEntity<ApiResponse<Integer>> getChapterLevel(
            @Parameter(description = "章节ID") @PathVariable Integer id) {
        int level = chapterService.getChapterLevel(id);
        return ResponseEntity.ok(ApiResponse.success(level));
    }

    @GetMapping("/api/courses/{courseId}/chapters/next-sort")
    @Operation(summary = "获取下一个可用的章节序号")
    @PreAuthorize("hasAnyRole('TEACHER', 'ADMIN')")
    public ResponseEntity<ApiResponse<Integer>> getNextSort(
            @Parameter(description = "课程ID") @PathVariable Integer courseId,
            @Parameter(description = "父章节ID（可选）") @RequestParam(required = false) Integer parentId) {
        Integer nextSort = chapterService.getNextSort(courseId, parentId);
        return ResponseEntity.ok(ApiResponse.success(nextSort));
    }
}